package com.example.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class RocketMQProducerService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 注入配置文件中的topic和default-topic
    @Value("${rocketmq.topic}")
    private String defaultTopic;

    @Value("${rocketmq.default-topic}")
    private String defaultTopicForEmpty;

    /**
     * 发送消息到指定的topic或默认的topic
     *
     * @param topic   要发送的topic，如果为空则使用默认的topic
     * @param message 要发送的消息
     */
    public void sendMessage(String topic, String message) {
        // 如果 topic 为空，使用配置中的默认 topic
        String targetTopic = (topic == null || topic.isEmpty()) ? defaultTopic : topic;
        rocketMQTemplate.send(targetTopic, MessageBuilder.withPayload(message).build());
        log.info("Message sent to topic {}: {}", targetTopic, message);
    }

    /**
     * 发送消息到default-topic
     *
     * @param message 要发送的消息
     */
    public void sendMessageToDefaultTopic(String message) {
        rocketMQTemplate.send(defaultTopicForEmpty, MessageBuilder.withPayload(message).build());
        log.info("Message sent to default topic {}: {}", defaultTopicForEmpty, message);
    }
}
